<template>
  <uni-forms v-model="formData" ref="formRef">
    <block v-for="(item, index) in formSchema" :key="index">
      <uni-forms-item
        class="uni-forms-item"
        :label="item.label"
        :label-width="labelWidth"
        :required="item.require"
        :rules="item.rules"
        :key="item.field"
        :name="item.field"
      >
        <uni-easyinput
          v-if="item.component === 'uni-easyinput'"
          :ref="`${item.field}-ref`"
          v-bind="item.componentProps"
          v-model="formData[item.field]"
          @change="change($event, item)"
        ></uni-easyinput>
        <uni-data-checkbox
          v-if="item.component === 'uni-data-checkbox'"
          :ref="`${item.field}-ref`"
          v-bind="item.componentProps"
          v-model="formData[item.field]"
          @change="change($event, item)"
        ></uni-data-checkbox>
        <picker
          v-if="item.component === 'picker'"
          :ref="`${item.field}-ref`"
          class="picker"
          v-bind="item.componentProps || {}"
          :value="formData[item.field]"
          @change="change($event, item)"
        >
          <view
            v-if="formData[item.field]"
            class="uni-input"
            :class="formData[item.field]"
            >{{ formData[item.field] }}</view
          >
          <view v-else class="placeholder">请选择</view>
        </picker>
        <upload-image
          v-if="item.component === 'upload-image'"
          :ref="`${item.field}-ref`"
          v-bind="item.componentProps || {}"
          v-model="formData[item.field]"
          :action="imageAction"
          @change="change($event, item)"
        ></upload-image>
        <tree
          v-if="item.component === 'tree'"
          :ref="`${item.field}-ref`"
          v-bind="item.componentProps"
          @change="change($event, item)"
        ></tree>
        <div v-if="item.component === 'upload-video'">
          <!-- https://gateway.wxls.pro/pzsh/manager/pzshInformation/uploadVideo -->
          <htz-image-upload
            :ref="`${item.field}-ref`"
            v-bind="item.componentProps"
            name="file"
            :chooseNum="1"
            :compress="false"
            :cateId="videoCateId"
            :templateGroupId="videoTemplateGroupId"
            v-model="videoData"
            mediaType="video"
            @uploadSuccess="change($event, item)"
            @item="videoiItem($event, item)"
            @imgDelete="videoDelete($event, item)"
          >
          </htz-image-upload>
          <p class="tip-content">
            {{ item.componentProps.tip }}
          </p>
          <p v-if="type.value === 'update'" class="tip-content">
            注：刚上传的视频无法播放时，可能是在转码中或失效了
          </p>
        </div>
      </uni-forms-item>
    </block>
    <uni-forms-item>
      <button
        class="submit-button"
        :style="`background-color: ${submitButtonBackgroundColor};`"
        @click="submit"
      >
        {{ type.lable }}
      </button>
    </uni-forms-item>
  </uni-forms>
</template>

<script>
  import * as Api from '@/server/index.js';
  import uploadImage from './components/upload-image/upload-image.vue';
  import htzImageUpload from './components/htz-image-upload/aliyun_upload.vue';
  import tree from '@/components/form/components/tree/index.vue';

  export default {
    name: 'formsComp',
    components: { uploadImage, tree, htzImageUpload },
    props: {
      form: {
        // 接收的表单信息
        type: Object,
        default: () => {},
      },
      formSchema: {
        type: Array,
        require: true,
      },
      labelWidth: {
        // label的宽度，单位px
        type: Number,
        default: 70,
      },
      submitButtonBackgroundColor: {
        // 提交按钮背景色
        type: String,
        default: '#409EFF',
      },
      imageAction: {
        // 图片上传接口地址
        type: String,
        default: '',
      },
      videoTemplateGroupId: {
        // 视频转码模板
        type: String,
        default: 'e3b1454d853a1cfd097de6d54a4f13db', // 乐享生活圈模版
      },
      videoCateId: {
        // 视频媒资分类id
        type: Number,
        default: '',
      },
    },
    data() {
      return {
        formData: this.form || {},
        type: {
          lable: '',
          value: '',
        },
        videoData: [],
      };
    },

    mounted() {
      if (this.form && JSON.stringify(this.form) != '{}') {
        this.type.lable = '修改';
        this.type.value = 'update';
        this.form.video && this.getVideo();
      } else {
        this.type.lable = '提交';
        this.type.value = 'add';
      }
    },
    methods: {
      /**
       * 提交
       */
      submit(form) {
        this.$refs.formRef
          .validate((err, formData) => {
            // console.log('表单校验: >>', err, this.formData);
            // 如果校验成功 ，err 返回 null
            if (err) {
              // 未通过验证
              uni.showToast({
                title: err[0].errorMessage,
                icon: 'none',
                duration: 2000,
              });
              return;
            }
            // 通过验证
            uni.showModal({
              title: '提示',
              content: `确定${this.type.lable}？`,
              success: (res) => {
                if (res.confirm) {
                  this.$emit('submit', {
                    type: this.type.value,
                    form: this.formData,
                  });
                }
              },
            });
          })
          .then((res) => {
            console.log('表单数据信息：', res);
          })
          .catch((err) => {
            console.log('表单错误信息：', err);
          });
      },
      /**
       * 重置表单
       */
      resetForm() {
        // this.formData = {};
        this.formData = this.form || {};
        this.videoData = [];
      },

      change(e, item) {
        switch (item.component) {
          case 'picker':
            this.$set(this.formData, item.field, e.detail.value);
            break;
          case 'upload-image':
            this.$set(this.formData, item.field, e);
            break;
          case 'tree':
            this.$set(this.formData, item.field, e[0].id);
            break;
          case 'upload-video':
            this.$set(this.formData, item.field, e.videoId);
            break;
          default:
            break;
        }
        this.$emit('change', e);
      },

      async getVideo() {
        uni.showLoading();
        const videoId = this.form.video;
        try {
          const res = await Api.video.videoUrl(videoId);
          if (!res.data.data) {
            uni.showToast({
              title: '视频转码中或失效了',
              icon: 'none',
            });
          }
          this.videoData = [
            res.data.data.playInfoList
              ? res.data.data.playInfoList[
                  res.data.data.playInfoList.length - 1
                ].playUrl
              : res.data.data.fileUrl,
          ];
        } catch (e) {
        } finally {
          uni.hideLoading();
        }
      },
      /* zidingyiSuccess(res) {
			  console.log('zidingyiSuccess', res);
			  // this.video= res.data.data
			  this.form.video = res.videoId;
			}, */
      videoiItem(e, item) {
        console.log('item', e);
        this.videoData = [e.url];
      },
      videoDelete(e, item) {
        console.log(e);
        this.formData[item.field] = '';
        this.videoData = [];
      },
    },
  };
</script>

<style lang="scss" scoped>
  .uni-forms-item {
  }
  /deep/.uni-data-checklist {
    height: 100%;
    .checklist-group {
      height: 100%;
    }
  }

  .picker {
    width: 100%;
    height: 100%;
    display: flex;
    box-sizing: border-box;
    flex-direction: row;
    align-items: center;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding-left: 10px;
  }

  .placeholder {
    color: #999;
    font-size: 12px;
  }

  .submit-button {
    margin-top: 10px;
    border-radius: 30px;
    color: #fff;
    // background-image: linear-gradient(to bottom, #0e57118c, #49b01c);
  }

  .tip-content {
    color: #aaa;
    font-size: 24rpx;
    margin-top: 6rpx;
  }
</style>
